package com.denghq.projectbuilder.component.consul.service.impl;

import java.util.List;
import java.util.Map;

import com.denghq.projectbuilder.component.consul.service.Deregister;
import org.springframework.cloud.consul.serviceregistry.ConsulRegistration;
import org.springframework.stereotype.Component;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.Member;
import com.ecwid.consul.v1.agent.model.Service;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class DeregisterImp implements Deregister {


    private final ConsulClient consulClient;

    private final ConsulRegistration consulRegistration;

    public DeregisterImp(ConsulClient consulClient, ConsulRegistration consulRegistration) {
        this.consulClient = consulClient;
        this.consulRegistration = consulRegistration;
    }

    @Override
    public void deregister() {
        String currentInstanceId = consulRegistration.getInstanceId();
        deregister(currentInstanceId);
    }

    @Override
    public void deregister(String currentInstanceId) {
        List<Member> members = consulClient.getAgentMembers().getValue();
        for (Member member : members) {
            String address = member.getAddress();
            ConsulClient clearClient = new ConsulClient(address);
            try {
                Map<String, Service> serviceMap = clearClient.getAgentServices().getValue();
                for (Map.Entry<String, Service> entry : serviceMap.entrySet()) {
                    Service service = entry.getValue();
                    String instanceId = service.getId();
                    if (currentInstanceId.equals(instanceId)) {
                        log.warn("在{}客户端上的服务 :{}为无效服务，准备清理...................", address, currentInstanceId);
                        clearClient.agentServiceDeregister(currentInstanceId);
                    }
                }
            } catch (Exception e) {
                log.error("异常信息: {}", e);
            }
        }
    }
}
